<template>
    <div class="white-box-form">
        <el-form
            ref="ruleRef"
            :model="state.ruleForm"
            :rules="state.rules"
            label-width="120px"
            class="mt-20"
        >
            <el-form-item label="商家名称" prop="storeName">
                <el-input
                    v-model.trim="state.ruleForm.storeName"
                    clearable
                    placeholder="请输入商家名称"
                />
            </el-form-item>
            <el-form-item label="开户人" prop="accountName">
                <el-input
                    v-model.trim="state.ruleForm.accountName"
                    clearable
                    placeholder="请输入开户人"
                />
            </el-form-item>
            <el-form-item label="开户行" prop="accountBank">
                <el-input
                    v-model.trim="state.ruleForm.accountBank"
                    clearable
                    placeholder="请输入开户行"
                />
            </el-form-item>
            <el-form-item label="开户账号" prop="accountBankNumber">
                <el-input
                    v-model.trim="state.ruleForm.accountBankNumber"
                    clearable
                    placeholder="请输入开户账号"
                />
            </el-form-item>
            <el-form-item label="对公账户" prop="accountNumber">
                <el-input
                    v-model.trim="state.ruleForm.accountNumber"
                    clearable
                    placeholder="请输入对公账户"
                />
            </el-form-item>
            <el-form-item label="法人姓名" prop="personName">
                <el-input
                    v-model.trim="state.ruleForm.personName"
                    clearable
                    placeholder="请输入法人姓名"
                />
            </el-form-item>
            <el-form-item label="法人身份证号" prop="personNumber">
                <el-input
                    v-model.trim="state.ruleForm.personNumber"
                    clearable
                    placeholder="请输入法人身份证号"
                    max-length="18"
                />
            </el-form-item>
            <el-form-item label="法人手机号" prop="personPhone">
                <el-input
                    v-model.trim="state.ruleForm.personPhone"
                    clearable
                    placeholder="请输入法人手机号"
                    max-length="11"
                />
            </el-form-item>
            <el-form-item label="纳税识别号" prop="taxNumber">
                <el-input
                    v-model.trim="state.ruleForm.taxNumber"
                    clearable
                    placeholder="请输入纳税识别号"
                />
            </el-form-item>
            <el-form-item label="营业执照图片" prop="businessImgUrl">
                <el-upload
                    ref="uploadRef"
                    v-model:file-list="fileList"
                    v-loading="imgLoading"
                    :limit="1"
                    :class="{
                        'hide-upload-btn': state.ruleForm.businessImgUrl,
                    }"
                    :action="actionImgUrl()"
                    :http-request="uploadImg"
                    list-type="picture-card"
                    :on-remove="handleRemove"
                    :before-upload="beforeAvatarUpload"
                    :on-change="fileChange"
                    :on-preview="handlePreview"
                    :on-exceed="handleExceed"
                >
                    <el-icon color="#999">
                        <upload-filled />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-radio-group v-model="state.ruleForm.status">
                    <el-radio
                        v-for="item in state.statusList"
                        :key="item.memberKey"
                        :value="item.memberKey"
                        >{{ item.memberName }}</el-radio
                    >
                </el-radio-group>
            </el-form-item>
        </el-form>

        <div class="foot-btn">
            <el-button
                type="primary"
                :loading="state.form_loading"
                @click="submitForm(ruleRef)"
            >
                {{ isEdit ? "修改" : "添加" }}
            </el-button>
        </div>
        <go-back />
    </div>

    <el-dialog v-model="imgVisible">
        <img w-full :src="dialogImageUrl" />
    </el-dialog>
</template>

<script setup>
import { inject, ref, onMounted, reactive, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import GoBack from "@components/GoBack.vue";

import UploadImg from "@/mixins/upload-img";
import { validPhone, validIdCard } from "@/assets/common/utils";
import { getStoreDetail, addStore, editStore } from "@/apis/store/store";
import { useDictStore } from "@stores/dict.js";

const dictStore = useDictStore();
dictStore.getDictMembers("data_status").then((res) => (state.statusList = res));
dictStore
    .getDictMembers("deletable")
    .then((res) => (state.deletableList = res));

const router = useRouter();
const route = useRoute();

const $message = inject("$message");
const imgUrl = inject("imgUrl");

const sid = route.query.sid;
const isEdit = ref(false);
const form_loading = ref(false);
const ruleRef = ref(null);
const state = reactive({
    statusList: [],
    deletableList: [],
    ruleForm: {
        status: 0,
        storeName: null,
        accountName: null,
        accountBank: null,
        accountBankNumber: null,
        accountNumber: null,
        personName: null,
        personNumber: null,
        personPhone: null,
        taxNumber: null,
        businessImgUrl: null,
    },
    rules: {
        storeName: [
            { required: true, message: "请输入商家名称", trigger: "blur" },
        ],
        accountName: [
            { required: true, message: "请输入开户人", trigger: "blur" },
        ],
        accountBank: [
            { required: true, message: "请输入开户行", trigger: "blur" },
        ],
        accountBankNumber: [
            { required: true, message: "请输入开户账号", trigger: "blur" },
        ],
        accountNumber: [
            { required: true, message: "请输入对公账户", trigger: "blur" },
        ],
        personName: [
            { required: true, message: "请输入法人姓名", trigger: "blur" },
        ],
        personNumber: [
            { required: true, validator: validIdCard, trigger: "blur" },
        ],
        personPhone: [
            { required: true, validator: validPhone, trigger: "blur" },
        ],
        taxNumber: [
            { required: true, message: "请输入纳税识别号", trigger: "blur" },
        ],
        businessImgUrl: [
            { required: true, message: "请上传营业执照", trigger: "blur" },
        ],
    },
});

onMounted(() => {
    if (/Edit$/.test(route.name)) {
        isEdit.value = true;
        getDetail();
    }
});

const getDetail = async () => {
    const res = await getStoreDetail({ sid });
    if (res.data.code == 200) {
        state.ruleForm = res.data.data;
        if (state.ruleForm.businessImgUrl) {
            const arr = state.ruleForm.businessImgUrl.split("/");
            fileList.value.push({
                name: arr[arr.length - 1],
                url: imgUrl + state.ruleForm.businessImgUrl,
            });
        }
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 提交表单
const submitForm = (formEl) => {
    if (!formEl) return;
    formEl.validate(async (valid, fields) => {
        if (valid) {
            form_loading.value = true;
            let res = null;
            if (isEdit.value) {
                res = await editStore(state.ruleForm);
            } else {
                res = await addStore(state.ruleForm);
            }
            form_loading.value = false;
            if (res.data.code == 200) {
                $message({
                    message: isEdit.value ? "修改成功" : "添加成功",
                    type: "success",
                });
                router.back();
            } else {
                $message({ message: res.data.msg, type: "error" });
            }
        }
    });
};

const uploadRef = ref(null);
const {
    succList,
    imgLoading,
    handlePreview,
    actionImgUrl,
    uploadImg,
    handleRemove,
    beforeAvatarUpload,
    fileChange,
    handleExceed,
    imgVisible,
    dialogImageUrl,
    fileList,
} = UploadImg();
watch(
    succList,
    (newVal) => {
        state.ruleForm.businessImgUrl = newVal;
    },
    { deep: true }
);
</script>
